package asia.redact.bracket.properties;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;


public class ServerLocalizedFileFinder {

	File parentFolder;
	String baseName;
	
	private ServerLocalizedFileFinder(){}
	
	public ServerLocalizedFileFinder(File parentFolder, String baseName) {
		this();
		this.parentFolder = parentFolder;
		// trim if needed
		if(baseName.endsWith(".properties")){
			this.baseName = baseName.substring(0,baseName.length()-11);
		}else {
			this.baseName = baseName;
		}
	}
	
	/**
	 * find all of the files in a given set for a base name. return in appropriate order
	 * 
	 * @return
	 */
	public File[] findFiles() {
		File [] files = parentFolder.listFiles(new MyFileFilter(baseName));
		if(files.length>1) Arrays.sort(files, new MyComparator());
		return files;
	}
	
	/**
	 * return only the subset of matching files given a ServerLocale
	 * 
	 * @param locale
	 * @return
	 */
	public ArrayList<File> findMatching(ServerLocale locale){
		ArrayList<File> list = new ArrayList<File>();
		for(File file: findFiles()){
			if(locale.includes(file.getName())){
				list.add(file);
			}
		}
		return list;
	}
	
	class MyComparator implements Comparator<File> {

		public int compare(File o1, File o2) {
			String name0 = o1.getName();
			String name1 = o2.getName();
			int c0 = countUnderscores(name0);
			int c1 = countUnderscores(name1);
			int resultUnderscores = 0;
			if(c0>c1) resultUnderscores = 1;
			if(c0<c1) resultUnderscores = -1;
			
		//	if(resultUnderscores==0){
			//	return name0.compareTo(name1);
		//	}
			 return resultUnderscores;
			
		}
		
		private int countUnderscores(final String s) {
			int count = 0;
			for(int i = 0; i<s.length();i++){
				if(s.charAt(i)=='_')count++;
			}
			return count;
		}
		
	}
	
	class MyFileFilter implements FileFilter {
		
		String baseName;

		public MyFileFilter(String baseName) {
			super();
			this.baseName = baseName;
		}

		public boolean accept(File pathname) {
			if(pathname.isFile()&& 
					pathname.getName().startsWith(baseName)&&
					pathname.getName().endsWith(".properties")) return true;
			return false;
		}
	}
}
